/**
 * @author madStone_l
 */
// Ext.ns('Ext.ux.form');
Ext.define('Sys.ux.SearchField', {
	extend : 'Ext.form.field.Trigger',
	alias : 'widget.searchtrigger',
	validationEvent : false,
	validateOnBlur : false,
	trigger1Cls : 'x-form-clear-trigger',
	trigger2Cls : 'x-form-search-trigger',
	hideTrigger1 : true,
	width : 180,
	hasSearch : false,
	paramName : 'query',
	regex : /^[\u4E00-\u9Fa5_a-zA-Z0-9]+$/,
	regexText : '远程搜索只允许输入汉字,字母,数字,下划线',
	initComponent : function() {
		this.callParent(arguments);
		this.on({
					specialkey : {
						scope : this,
						fn : function(f, e) {
							if (e.getKey() == e.ENTER) {
								this.onTrigger2Click();
							}
						}
					},
					keydown : {
						scope : this,
						fn : this.doFilter,
						buffer : 500
					}
				});
	},
	constructor : function(c) {
		c.enableKeyEvents = true;
		this.callParent(arguments);
	},
	onTrigger1Click : function() {
		if (this.hasSearch) {
			Ext.Function.defer(this.setValue, 1, this, ['']);
			var o = {
				start : 0
			};
			this.store.baseParams = this.store.baseParams || {};
			this.store.baseParams[this.paramName] = '';
			this.store.proxy.params = o;
			this.store.load();
			this.triggerEl.elements[0].parent().setWidth(0);
			this.hasSearch = false;
			this.focus();
		}
	},

	onTrigger2Click : function() {
		var v = this.getRawValue();
		if (v.length < 1) {
			this.onTrigger1Click();
			return;
		}
		if (v.length < 2) {
			Ext.Msg.showWarning('您至少需要输入2个字符才能执行远程搜索', function() {
						this.focus(true);
					}, this);
			return;
		}
		if (!this.isValid(true)) {
			Ext.Msg.showWarning(this.regexText, function() {
						this.focus(true);
					}, this);
			return;
		}
		this.store.clearFilter(true);
		var o = {
			start : 0
		};
		this.store.baseParams = this.store.baseParams || {};
		this.store.baseParams[this.paramName] = v;
		this.store.proxy.params = o;
		this.store.load();
		this.hasSearch = true;
		this.triggerEl.elements[0].parent().setWidth(this.triggerWidth);
	},
	doFilter : function(t, e) {
		var value = t.getValue();
		if (Ext.isEmpty(value))
			this.store.clearFilter();
		else {
			var fields = [];
			var grid = this.ownerCt.ownerCt;
			if (grid && Ext.isFunction(grid.getColumnModel)) {
				var c = grid.getColumnModel().config;
				Ext.each(c, function(v, i, a) {
							if (!Ext.isEmpty(v.dataIndex) && v.hidden !== true)
								fields.push(v.dataIndex)
						});
			} else
				fields.push(this.store.fields.keys);
			this.store.filterBy(function(r, id) {
						var re = false;
						Ext.each(fields, function(v, i, a) {
									if (r.get(v)) {
										re = r.get(v).toString().toUpperCase()
												.indexOf(value.toUpperCase()) != -1;
										return !re;
									}
								}, this);
						return re;
					}, this);
		}

	}
});